<?php

/**
 * @desc 基本鉴权控制器
 * @author  tom_xia 
 */
require_once APPPATH."/libraries/Jredis.php";
class BasePriv extends CI_Controller {

    public $userInfo = '';
    public $preMenuPage = "";//用户上一次访问的菜单页
    public $redis = null;

    public function __construct() {
        parent::__construct();

        $this->load->helper("url");
        $this->load->helper("common");
        $this->load->helper("cookie");
//        echo (microtime(true)*1000)."<br>";
        $this->redis = new Jredis(REDIS_HOST,REDIS_PORT,REDIS_TIMEOUT);
//        echo (microtime(true)*1000)."<br>";
//        exit;
        //判断用户是否登陆,并且用户是否有效
        $isLogin = false;
        if (!empty(get_cookie("user_info"))) {
            $isLogin = true;
            $userInfo = unserialize(auth_code(get_cookie("user_info")));
            $this->userInfo = $userInfo;
        }
        if (!$isLogin) {
            //如果用户没有登陆，那么跳转到登陆页面或者返回一个错误信息
            if (isset($_SERVER["HTTP_X_REQUESTED_WITH"])) {
                //ajax
                echo "invalid-session";
                exit;
            } else {
                echo "<script>top.location.href='" . base_url("site") . "'</script>";
                exit;
            }
        }


        $uri = strtolower(strval($this->router->directory) . $this->router->class . "/" . $this->router->method);

    }

    //渲染左导航和顶部导航
    public function layout($view = "", array $data = []) {
        $this->load->view("top",$this->userInfo);
        $this->load->view("left",["menu"=> strval($this->router->directory) . $this->router->class,
            "userInfo"=>$this->userInfo,"path"=>strval($this->router->directory) . $this->router->class."/".$this->router->method,
        ]);
        if($view){
            $this->load->view($view,$data);
        }
        $this->load->view("bottom");
    }

    /**
     * @desc 简化post
     * @param string $key
     * @param bool $xss
     * @return mixed
     */
    public function post($key = null, $xss = false) {
        return $this->input->post($key, $xss);
    }

    /**
     * @desc 简化get
     * @param string $key
     * @param bool $xss
     * @return mixed
     */
    public function get($key = null, $xss = false) {
        return $this->input->get($key, $xss);
    }
    public function isAjax(){
        return isset($_SERVER["HTTP_X_REQUESTED_WITH"]) ? true  :false;
    }
    public function createBtn(array $params,$isHref=true)
    {
        extract($params);
        $uri = isset($uri) ? $uri : '';
        $text = isset($text) ? $text : '按钮';
        $href = isset($href) ? $href : site_url($uri);
        $event = isset($event) ? "lay-event='{$event}'" : '';
        $attr = isset($attr) ? $attr : "";
        $btnClass = isset($btnClass)&&$btnClass ? $btnClass : "layui-btn-sm layui-btn-normal";
        $str = "<a class=\"layui-btn {$btnClass}\" {$event} $attr";
        if(isset($onclick)&&$onclick){
            $onclick = str_replace("'", "\"", $onclick);
            $str .= " onclick='{$onclick}' href='javascript:;' ";
        }elseif($isHref){
            $str .= " href='".$href."' ";
        }
        if(isset($initStyle)&&$initStyle){
            $str .= " style='{$initStyle}' ";
        }
        $str .= ">{$text}</a>";
        return $str;
    }

    /**
     * @desc简化request
     * @param null $key
     * @return null
     */
    public function request($key = null) {
        if (isset($key)) {
            if (isset($_REQUEST[$key])) {
                return $_REQUEST[$key];
            } else {
                return null;
            }
        }
        return $_REQUEST;
    }

    /**
     * @desc 获取序列号
     * @param $page 当前页
     * @param $pageSize 每页大小
     * @param $index 当前数据索引
     * @return mixed
     */
    public function getSerialNum($page,$pageSize,$index)
    {
        return  ($page-1)*$pageSize+$index+1; ;
    }

    /**
     * @param $date日期 /时间
     * @param bool $is_time 是否是具体时间
     * @return false|string
     */
    public function formatDate($date,$is_time=false)
    {
        if(!$is_time){
            $pattern = '/\d{4}-\d{2}-\d{2}/';
        }else{
            $pattern  = '/\d{4}-\d{2}-\d{2}/\s\d{2}:\d{2}:\d{2}';
        }
        $matchNums = preg_match($pattern,$date);
        if($matchNums == 0){
            return $is_time ? date("Y-m-d H:i:s") : date("Y-m-d");
        }else{
            return $date;
        }
    }
    /**
     * 获取请求的开始和结束时间
     */
    public function getStartAndEndTime($method="post",$useDefaultTimeType=true,$isUnixTimestamp=false)
    {
        $_time = [null,null];
        if(!empty($this->input->$method("time"))){
            $time = explode("~",$this->input->$method("time"),2);
            $_time[0] = $time[0];
            $_time[1] = $time[1];
        }
        if(!empty($this->input->$method("time_type"))){
            if($useDefaultTimeType){
                switch($this->input->$method("time_type")){
                    case 1:$startTime = date("Y-m-d",time()-2*86400);$endTime=date("Y-m-d",time());break;
                    case 2:$startTime = date("Y-m-d",time()-6*86400);$endTime=date("Y-m-d",time());break;
                    case 3:$startTime = date("Y-m-d",time()-29*86400);$endTime=date("Y-m-d",time());break;
                    case 4:$startTime = date("Y-m-d",time()-1*86400);$endTime=date("Y-m-d",time()-1*86400);break;
                    default:$startTime = null;$endTime=null;break;
                }
            }else{
                $startTime = date("Y-m-d",time()-$this->input->$method("time_type")*86400);$endTime=date("Y-m-d",time());
            }
            $_time[0] = $startTime;
            $_time[1] = $endTime;
        }
        if($_time[0] && $_time[1] && $isUnixTimestamp){
            $_time[0] = strtotime($_time[0]);
            $_time[1] = strtotime($_time[1]);
        }
        return $_time;
    }

    /**
     * 防止重复提交数据
     * @param array $data
     */
    protected function protectRepateData(array $data,$userId = "")
    {

        $dataPasswd = "cctv_protect_re_data_".md5(serialize($data)).$userId;
        $isExist = $this->redis->exists($dataPasswd);
        if($isExist){
            response(-1,"操作过于频繁,最后一次操作被忽略");
        }
        $this->redis->setEx($dataPasswd,1,5);
    }

    //
    public function output($code,$msg,$data=null,$count=null)
    {
        @ob_clean();
        header("Content-type:application/json");
        $datas['code']=$code;
        $datas['msg']=$msg;
        $datas['data']=$data;
        $datas['count']=$count;
        echo json_encode($datas,JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * 返回上传地址
     */
    public function upload_dir($type="image",$suffix="png"){
        //解决跨域问题
        $this->config->load("upload");
        $uploadConfigs = config_item("upload");
        //创建上传目录，配置上传
        $date1=date("Y",time());
        $date2=date("m",time());
        $date3=date("d",time());
        $dir="/".$date1."/".$date2."/".$date3;
        $uploadpath1=$uploadConfigs[$type]['uploadpath'];
        $uploadpath2=$uploadConfigs[$type]['savehttp'];
        $key1=rand(1000,10000);
        $key2=rand(10000,20000);
        $key3=rand();
        $file_name=$key1.$key2.$key3;
        //这是服务器上的上传地址
        $uploadpath['uploadpath']=$uploadpath1.$dir."/".$file_name.".{$suffix}";
        if($type=="video"){
            mkdir($uploadpath1.$dir."/".$file_name,0777,true);
        }
        //这是网络访问地址
        $uploadpath['savehttp']=$uploadpath2.$dir."/".$file_name.".{$suffix}";
        return $uploadpath;
    }

    /**
     * 返回临时存储目录
     */
    public function tmp_dir($type="test"){
        //解决跨域问题
        $this->config->load("upload");
        $uploadConfigs = config_item("upload");
        //创建上传目录，配置上传
        $date1=date("Y",time());
        $date2=date("m",time());
        $date3=date("d",time());
        $dir="/".$date1."/".$date2."/".$date3;
        $uploadpath1=$uploadConfigs[$type]['tmppath'];
        //这是服务器上的上传地址
        $uploadpath=$uploadpath1.$dir;
        return $uploadpath;
    }


}
